using System;
using IrisGenerator.Common.Core;
using System.ComponentModel;
using IrisGenerator.Common.Modules.Rules;
using IrisGenerator.Framework.RuleEngine;
using IrisGenerator.Framework.Events;
namespace IrisGenerator.Common.Modules
{
    
    
    public partial class Module : BindableObject<Module>,IRuleable<Module>, INotifyPropertyChanged
    {

        public bool IsDirty { get;private set; }


        public event EventHandler<BaseEventArgs<Module>> Inserting;
        public event EventHandler<BaseEventArgs<Module>> Inserted;
        public event EventHandler<BaseEventArgs<Module>> Deleting;

        public Module()
        {
            this.Rules = new ModuleRule(this);
        }

        protected void OnDeleting(BaseEventArgs<Module> e)
        {
            if (Deleting != null)
                Deleting(this, e);
        }

        protected void OnInserting(BaseEventArgs<Module> e)
        {
            if (Inserting != null)
                Inserting(this, e);
        }
        protected void OnInserted(BaseEventArgs<Module> e)
        {
            if (Inserted != null)
                Inserted(this, e);
        }
        protected void OnPropertyChanged(string PropertyName)
        {
            this.IsDirty = true;

            if (this.PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
        }
        

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion


        #region IRuleable Members

        public RuleBase<Module> Rules { get; private set; }
        
        public ModuleRule ObjectRules
        {
            get
            {
                return this.Rules as ModuleRule;
            }
        }

        #endregion

        public override bool Delete()
        {
            return this.Delete(false);
        }

        public bool RecursiveInsert()
        {
            this.Insert();
            foreach (ModuleParameter mp in this.ModuleParameterCollection)
            {
                mp.Module = this;
                mp.Insert();
            }
            return true;
        }

        public bool RecursiveUpdate()
        {
            this.Update();
            foreach (ModuleParameter mp in this.ModuleParameterCollection)
            {
                if (ModuleParameter.Exists(mp.ModParName, mp.Module))
                {
                    ModuleParameter tmp = ModuleParameter.Find(mp.ModParName, mp.Module);
                    mp.ModParId = tmp.ModParId;
                    mp.Update();
                }
                else
                    mp.Insert();
            }
            return true;
        }

        
    }
}
